package com.wfw.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wfw.enums.ProductStatusEnum;
import com.wfw.enums.ResultEnum;
import com.wfw.exception.SellException;
import com.wfw.mapper.ProductInfoMapper;
import com.wfw.model.OrderDetail;
import com.wfw.model.ProductInfo;
import com.wfw.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Override
    public ProductInfo findOne(String productId) {
        return productInfoMapper.selectByPrimaryKey(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoMapper.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findAll() {
        return productInfoMapper.findAll();
    }

    @Override
    public int save(ProductInfo productInfo) {
        ProductInfo productInfo1=productInfoMapper.selectByPrimaryKey(productInfo.getProductId());
        if (productInfo1==null||productInfo1.getProductId()==null){
            return productInfoMapper.insertSelective(productInfo);
        }else {
            return productInfoMapper.updateByPrimaryKeySelective(productInfo);
        }
    }

    @Override
    public void increaseStock(List<OrderDetail> orderDetailList) {
        orderDetailList.forEach(orderDetail -> {
            ProductInfo productInfo=productInfoMapper.selectByPrimaryKey(orderDetail.getProductId());
            if (productInfo==null||productInfo.getProductId()==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer restQuantity=productInfo.getProductStock()+orderDetail.getProductQuantity();

            productInfo.setProductStock(restQuantity);
            productInfoMapper.updateByPrimaryKeySelective(productInfo);
        });
    }

    @Override
    public void decreaseStock(List<OrderDetail> orderDetailList) {
        orderDetailList.forEach(orderDetail -> {
            ProductInfo productInfo=productInfoMapper.selectByPrimaryKey(orderDetail.getProductId());
            if (productInfo==null||productInfo.getProductId()==null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer restQuantity=productInfo.getProductStock()-orderDetail.getProductQuantity();
            if (restQuantity<0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(restQuantity);
            productInfoMapper.updateByPrimaryKeySelective(productInfo);
        });
    }
}
